package uk.co.wroedevelopments.semanticworkbench.parser;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import java.util.List;

import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.Resource.Diagnostic;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.parser.IParser;
import org.eclipse.xtext.parser.antlr.IAntlrParser;
import org.eclipse.xtext.parsetree.SyntaxError;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.util.StringInputStream;
import org.xtext.example.SemDslStandaloneSetup;
import org.xtext.example.semDsl.Ontology;

import com.google.inject.Injector;


public class ParserUtils {
	EList<Diagnostic> errors;
	private Injector inj;
	private IAntlrParser parser;
	private XtextResourceSet resourceSet;
	
	public ParserUtils() {
		new org.eclipse.emf.mwe.utils.StandaloneSetup().setPlatformUri("../");
		inj = new SemDslStandaloneSetup().createInjectorAndDoEMFRegistration();
		resourceSet = inj.getInstance(XtextResourceSet.class);
		resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);

		parser = inj.getInstance(IAntlrParser.class);
	}

	public EList<Diagnostic> getErrors() {
		return errors;
	}

	public Ontology getOntologyRoot(String t) throws IOException {
		
		Resource resource = resourceSet.createResource(URI.createURI("dummy:/example.semdsl"));
		InputStream in = new ByteArrayInputStream(t.getBytes());
		resource.load(in, resourceSet.getLoadOptions());
		Ontology ont = (Ontology) resource.getContents().get(0);
		errors = resource.getErrors();
//		IParseResult result = parser.parse(new StringInputStream(t));
//		errors = result.getParseErrors();
//		Ontology ont = (Ontology) result.getRootASTElement();
//		EcoreUtil.resolveAll(ont);
		return ont;
	}

}
